class smx_couchdb::install {

  package { $smx_couchdb::package::dependencies:
    ensure => 'installed',
  }
  user { 'couchdb':
    ensure      => present,
    home        => '/usr/local/couchdb/var/lib/couchdb',
    managehome  => false,
    comment     => 'CouchDB Administrator',
    shell       => '/bin/bash'
  }

  Exec {
    unless => '/usr/bin/test -f /usr/local/couchdb/bin/couchdb',
  }

  exec { 'download':
    cwd     => $smx_couchdb::cwd,
    command => "/usr/bin/wget -q ${smx_couchdb::download} -O ${smx_couchdb::filename}",
    timeout => '300',
  }

  exec { 'extract':
    cwd     => $smx_couchdb::cwd,
    command => "/bin/tar -xzvf ${smx_couchdb::filename}",
    timeout => '120',
    require => Exec['download'],
  }

  exec { 'configure':
    cwd         => "${smx_couchdb::cwd}/${smx_couchdb::foldername}",
    environment => 'HOME=/root',
    command     => "${smx_couchdb::cwd}/${smx_couchdb::foldername}/configure ${smx_couchdb::package::buildoptions}",
    timeout     => '600',
    require     => [
      Exec['extract'],
      Package[$smx_couchdb::package::dependencies]
    ],
  }

  exec { 'make-install':
    cwd         => "${smx_couchdb::cwd}/${smx_couchdb::foldername}",
    environment => 'HOME=/root',
    command     => '/usr/bin/make && /usr/bin/make install',
    timeout     => '600',
    require     => Exec['configure'],
  }

  File {
    owner   => 'couchdb',
    group   => 'couchdb',
    mode    => '0700',
    require => [
      Exec['make-install'],
      User['couchdb']
    ],
  }

  file {
    ['/usr/local/couchdb/var/lib/couchdb', '/usr/local/couchdb/etc/couchdb',
      '/usr/local/couchdb/var/log/couchdb', '/usr/local/couchdb/var/run/couchdb']:
      ensure  => directory,
  }

  file { '/etc/init.d/couchdb':
    ensure  => link,
    target  => '/usr/local/couchdb/etc/rc.d/couchdb',
  }

  file { '/usr/local/couchdb/etc/couchdb/local.ini':
    ensure  => file,
    mode    => '0600',
    source  => "puppet:///modules/smx_couchdb/local.ini",
    require => Exec['make-install'],
    notify  => Service['couchdb'];
  }
}
